<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Base64 编码</title>
    <link rel="stylesheet" href="../style/common.css">
    <style>
        .action {
            user-select: none;
        }

        #file {
            display: none;
        }

        #result {
            padding: 10px;
            width: 100%;
            box-sizing: border-box;
        }

        #copy {
            display: none;
        }
    </style>
</head>
<body>
    <div class="action">
        <label class="button button--primary" for="file">
            选取图像
            <input type="file" id="file" name="file">
        </label>
        
        <div class="button" id="copy">复制编码</div>
    </div>

    <div>
        <textarea id="result" placeholder="Base64 编码" rows="10"></textarea>
    </div>

    <script type="module">
        import { $ } from '../js/dom.js';
        import { copy } from '../js/clipboard.js';

        init();

        function init() {
            $('#file').addEventListener('change', processFile);
            $('#copy').addEventListener('click', onCopy);
        }

        function onCopy() {
            copy($('#result').value);
        }

        function processFile(e) {
            const files = e.target.files;
            if (files.length <= 0) {
                toggleButton(false);
                return;
            };
            
            encodeFile(files[0]);
            toggleButton(true);
        }

        function encodeFile(file) {
            const reader = new FileReader();
            reader.onload = onReaderLoaded;
            reader.readAsDataURL(file);
        }

        function onReaderLoaded(e) {
            $('#result').value = e.target.result;
        }

        function toggleButton(value) {
            const btn = $('#copy');
            if (value) {
                btn.style.display = 'inline-block';
            } else {
                btn.style.display = 'none';
            }
        }
    </script>
</body>
</html>